import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { GenerateQuery, WhereType } from '../../common/interfaces/basetype.interface'
import { ResponseData } from '../../common/interfaces/result.interface'
import { resSuccess } from '../../common/utils/response.util'
import { User } from '../user/user.entity'
import { CreateRoleDto } from './dto/create-role.dto'
import { UpdateRoleDto } from './dto/update-role.dto'
import { Role } from './role.entity'

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role) private readonly roleRepository: Repository<Role>,
    @InjectRepository(User) private readonly userRepository: Repository<User>,
  ) {}

  async findOne(id: number): Promise<ResponseData> {
    const result = await this.roleRepository.findOne(id)
    return resSuccess('', result)
  }

  async findAll({ pageSize = 2, page = 1, name, title }: GenerateQuery): Promise<ResponseData> {
    const where: WhereType = {}
    name && (where.name = Like(`%${name}%`))
    // title && (where.title = Like(`%${title}%`))
    title && (where.title = title)

    const result = await this.roleRepository.find({
      where,
      skip: (page - 1) * pageSize,
      take: pageSize,
    })
    return resSuccess('', result)
  }

  async create(dto: CreateRoleDto): Promise<ResponseData> {
    const result = await this.roleRepository.save(dto)
    return resSuccess('添加成功', result)
  }

  async update(id: number, dto: UpdateRoleDto): Promise<ResponseData> {
    const result = await this.roleRepository.update(id, dto)
    return resSuccess('编辑成功', result)
  }

  async delete(id: number): Promise<ResponseData> {
    const result = await this.roleRepository.delete(id)
    return resSuccess('删除成功', result)
  }
}
